//package com.info.zhiduoduo.core.service.payment.project;
//
//import com.baomidou.mybatisplus.mapper.Condition;
//import com.info.zhiduoduo.common.configs.CommonConfig;
//import com.info.zhiduoduo.common.configs.KltPayConfig;
//import com.info.zhiduoduo.common.configs.PayConfig;
//import com.info.zhiduoduo.common.configs.ZddUrlConfig;
//import com.info.zhiduoduo.common.constants.Constants;
//import com.info.zhiduoduo.common.constants.SmartResult;
//import com.info.zhiduoduo.common.constants.StatusMsg;
//import com.info.zhiduoduo.common.constants.system.UserType;
//import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowAccountType;
//import com.info.zhiduoduo.common.constants.company.CompanyAccountFlowBizType;
//import com.info.zhiduoduo.common.constants.company.CompanyPayType;
//import com.info.zhiduoduo.common.constants.pay.PayAccount;
//import com.info.zhiduoduo.common.constants.project.CompanyProjectState;
//import com.info.zhiduoduo.common.exception.RollbackException;
//import com.info.zhiduoduo.common.exception.SmartException;
//import com.info.zhiduoduo.common.utils.RandomUtil;
//import com.info.zhiduoduo.common.utils.StringUtil;
//import com.info.zhiduoduo.core.service.CoreBrokerageService;
//import com.info.zhiduoduo.core.service.CoreCompanyService;
//import com.info.zhiduoduo.core.service.CoreProjectService;
//import com.info.zhiduoduo.core.service.DingdingNoticeService;
//import com.info.zhiduoduo.core.service.WxCrowdsourceMessageService;
//import com.info.zhiduoduo.core.service.WxMessageService;
//import com.info.zhiduoduo.core.service.WxPartnerMessageService;
//import com.info.zhiduoduo.core.service.ZhiduoduoProjectService;
//import com.info.zhiduoduo.core.service.impl.CeoNoticeService;
//import com.info.zhiduoduo.core.service.payment.thirdpay.DaysPayService;
//import com.info.zhiduoduo.core.service.payment.thirdpay.KltPayService;
//import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
//import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
//import com.info.zhiduoduo.repository.entity.company.CompanyAccountflow;
//import com.info.zhiduoduo.repository.entity.company.CompanyProject;
//import com.info.zhiduoduo.repository.entity.maker.MakerBankcard;
//import com.info.zhiduoduo.repository.entity.order.TradeRecord;
//import com.info.zhiduoduo.repository.mapper.company.CompanyProjectMapper;
//import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceAccountMapper;
//import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectItemMapper;
//import com.info.zhiduoduo.repository.mapper.crowdsource.CrowdsourceProjectMapper;
//import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
//import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
//import com.info.zhiduoduo.repository.mapper.partner.PartnerBrokerageMapper;
//import com.info.zhiduoduo.repository.mapper.partner.PartnerCompanyMapper;
//import com.info.zhiduoduo.repository.mapper.partner.PartnerMapper;
//import com.info.zhiduoduo.repository.mapper.partner.PartnerSubMapper;
//import com.info.zhiduoduo.repository.mapper.system.ProjectCategoryMapper;
//import com.info.zhiduoduo.repository.mapper.taxer.TaxerInvoiceMapper;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.math.BigDecimal;
//import java.util.Arrays;
//import java.util.Date;
//
//import lombok.extern.slf4j.Slf4j;
//
///**
// * 企业使用自有的商户号支付项目款的业务逻辑
// */
//@Slf4j
//@Service
//@Transactional
//public class ProjectOwnMerchantPaymentServiceImpl extends BaseProjectPaymentService {
//
//	@Autowired
//	MakerMapper makerMapper;
//	@Autowired
//	PartnerCompanyMapper partnerCompanyMapper;
//	@Autowired
//	PartnerBrokerageMapper partnerBrokerageMapper;
//	@Autowired
//	ProjectCategoryMapper projectCategoryMapper;
//	@Autowired
//	CompanyProjectMapper projectMapper;
//	@Autowired
//	CrowdsourceAccountMapper crowdsourceAccountMapper;
//	@Autowired
//	CrowdsourceProjectItemMapper crowdsourceProjectItemMapper;
//	@Autowired
//	CrowdsourceProjectMapper crowdsourceProjectMapper;
//	@Autowired
//	MakerStudioMapper makerStudioMapper;
//	@Autowired
//	TaxerInvoiceMapper taxerInvoiceMapper;
//	@Autowired
//	PartnerSubMapper partnerSubMapper;
//	@Autowired
//	PartnerMapper partnerMapper;
//
//	@Autowired
//	CoreCompanyService coreCompanyService;
//	@Autowired
//	DingdingNoticeService dingdingNoticeService;
//	@Autowired
//	WxMessageService wxMessageService;
//	@Autowired
//	WxPartnerMessageService wxPartnerMessageService;
//	@Autowired
//	WxCrowdsourceMessageService wxCrowdsourceMessageService;
//	@Autowired
//	CeoNoticeService ceoNoticeService;
//	@Autowired
//	CoreProjectService coreProjectService;
//	@Autowired
//	ZhiduoduoProjectService zhiduoduoProjectService;
//	@Autowired
//	CoreBrokerageService coreBrokerageService;
//	@Autowired
//	KltPayService kltPayService;
//	@Autowired
//	DaysPayService daysPayService;
//
//	@Autowired
//	CommonConfig commonConfig;
//	@Autowired
//	ZddUrlConfig zddUrlConfig;
//	@Autowired
//	PayConfig payConfig;
//	@Autowired
//	KltPayConfig kltPayConfig;
//
//	@Override
//	public void deductCompanyBalanceForPublishProject(CompanyAccount account, CompanyProject project) {
//		// 冻结企业金额
//		BigDecimal beforeFrozenBalance = account.getFrozenBalance();
//		account.setFrozenBalance(beforeFrozenBalance.add(project.getProjectamount()));
//		account.updateById();
//	}
//
//	@Override
//	public SmartResult handlePayment(CompanyProject project) {
//		handleCompanyAccountFlow(project);
//		handlePayJiugeCharge(project);
//		return handlePayUser(project);
//	}
//
//	private void handleCompanyAccountFlow(CompanyProject project) {
//		//生成企业流水
//		String username = "";
//		MakerDetailDto userInfo = makerMapper.getUserDetail(project.getUserid());
//		if (userInfo != null) {
//			username = StringUtil.isEmpty(userInfo.getUsername()) ? userInfo.getRealname() : userInfo.getUsername();
//		}
//		CompanyAccountflow accountflow = new CompanyAccountflow().setCompid(project.getCompid())
//				.setFlowname(project.getProjectname() + "项目付款给创客" + username)
//				.setFlowtype(2)
//				.setBizid(project.getProjectid())
//				.setBizType(CompanyAccountFlowBizType.ZDD_PROJECT)
//				.setAccountType(CompanyAccountFlowAccountType.OWN_MERCHANT)
//				.setFlowAmount(getPayUserAmount(project));
//
//		CompanyAccountflow jiugeFlow = new CompanyAccountflow().setCompid(project.getCompid())
//				.setFlowname(project.getProjectname() + "项目平台服务费")
//				.setFlowtype(2)
//				.setBizid(project.getProjectid())
//				.setBizType(CompanyAccountFlowBizType.ZDD_PROJECT)
//				.setAccountType(CompanyAccountFlowAccountType.OWN_MERCHANT)
//				.setFlowAmount(project.getProjectservicecharge().add(project.getProjecttaxfee()));
//		if (accountflow.insert() && jiugeFlow.insert()) {
//			return;
//		}
//
//		throw SmartException.of("生成企业流水失败");
//	}
//
//	@Override
//	public SmartResult handlePayUser(CompanyProject project) {
//
//		Integer projectid = project.getProjectid();
//		Integer userid = project.getUserid();
//		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", project.getCompid()));
//
//		//实际给创客的金额
//		BigDecimal payUserAmount = getPayUserAmount(project);
//
//		//专票项目，使用对公账户，普票项目，使用个人账户
//		Integer invoicetype = project.getInvoicetype();
//		int accttype = invoicetype != null && invoicetype == 2 ? Constants.BANK_ACCT_TYPE_COMPANY : Constants.BANK_ACCT_TYPE_PERSONAL;
//		MakerBankcard bankcard = new MakerBankcard().selectOne(
//				Condition.create().eq("userid", userid).eq("state", 1).eq("accttype", accttype).last("limit 1"));
//
//		if (bankcard == null) {
//			return SmartResult.fail(StatusMsg.StatusMsg_206);
//		}
//
//		//支付记录,检查是否已存在还未处理好的支付记录.如果有,那么需要等待
//		//支付创建中,处理中和处理成功,表示不需要再新建了.直接返回
//		int recordProcessing = new TradeRecord().selectCount(Condition.create()
//				.eq("projectid", projectid)
//				.eq("idtype", UserType.MAKER)
//				.eq("business_type", Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
//				.in("tradestate", Arrays.asList(Constants.TRADE_CREATE, Constants.TRADE_IN_PROCESS)));
//		if (recordProcessing > 0) {
//			return SmartResult.fail(StatusMsg.StatusMsg_448);
//		}
//		int recordSuccess = new TradeRecord().selectCount(Condition.create()
//				.eq("projectid", projectid)
//				.eq("idtype", UserType.MAKER)
//				.eq("business_type", Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
//				.eq("tradestate", Constants.TRADE_SUCCESS));
//		if (recordSuccess > 0) {
//			return SmartResult.fail(StatusMsg.StatusMsg_449);
//		}
//
//		String purpose = project.getProjectname() + "-项目款";
//		if (purpose.length() > 16) {
//			purpose = purpose.substring(0, 16);
//		}
//
//		// 2020.6.6 根据项目的支付方式,确定商户号id:九歌统一账户或者企业自己的商户号
//		String merchantid;
//		int payAccount;
//		if (project.getPayType() != CompanyPayType.OWN_MERCHANT && StringUtil.isEmpty(companyAccount.getMerchantid())) {
//			// 没有绑定商户号, 报错,直接回滚所有操作
//			throw SmartException.of(StatusMsg.StatusMsg_329);
//		}
//		merchantid = companyAccount.getMerchantid();
//		payAccount = PayAccount.OWN_MERCHANT;
//
//		TradeRecord trade = new TradeRecord().setAcctname(bankcard.getPayername())
//				.setMerchantid(merchantid)
//				.setBankname(bankcard.getBankname())
//				.setBankno(bankcard.getBankno())
//				.setAcctno(bankcard.getAcctno())
//				.setAccttype(bankcard.getAccttype())
//				.setPurpose(purpose)
//				.setTradeamount(payUserAmount)
//				.setTradeno(RandomUtil.createRandomNo("PAY", ""))
//				.setTradetime(new Date())
//				.setTradetype(Constants.TRADE_TYPE_PAYMENT)
//				.setPayAccount(payAccount)
//				.setBusinessType(Constants.KLT_PAY_BUSINESS_TYPE_USER_AMOUNT)
//				.setProjectid(projectid)
//				.setIdtype(1)
//				.setUserid(userid);
//
//		if (trade.insert()) {
//			return kltPayService.doCallPayApi(trade);
//		}
//		return SmartResult.fail(StatusMsg.StatusMsg_445);
//	}
//
//	@Override
//	public void doAfterPayUserTradeSucceed(CompanyProject project, TradeRecord trade) {
//		if (project != null) {
//			project.setState(CompanyProjectState.COMPLETED).setProjectfinish(new Date()).updateById();
//			SmartResult smartResult = handleCompanyOrderInternal(project);
//
//			//当处理企业账户失败时，直接回滚
//			if (smartResult.isFailed()) {
//				throw new RollbackException("企业账户操作失败");
//			}
//
//			try {
//				zhiduoduoProjectService.handleUserProjectAccountFlow(project, trade.getTradeid());
//			} catch (Exception e) {
//				//报错,回滚
//				log.error("doAfterPayUserTradeSucceed 报错:", e);
//				throw new RollbackException("处理创客流水失败");
//			}
//		}
//	}
//
//	/**
//	 * 项目款已经成功交易给创客后，处理企业的订单状态
//	 *
//	 * @return 处理成功, 则返回正常, 否则返回错误状态
//	 */
//	public SmartResult handleCompanyOrderInternal(CompanyProject project) {
//
//		Integer projectid = project.getProjectid();
//		// Order order = new Order().selectOne(Condition.create().eq("projectid", projectid));
//		// if (order == null) return smartResult(StatusMsg.StatusMsg_301);
//
//		CompanyAccount account = new CompanyAccount().selectOne(Condition.create().eq("compid", project.getCompid()));
//		if (account == null) return SmartResult.fail(StatusMsg.StatusMsg_302);
//
//		//2019.6.2 没有开联通账户时，就用九歌统一账户
//		//2020.6.7 通过项目的payType来判断使用的支付账户
//		//恢复企业被冻结的余额
//		Integer payType = project.getPayType();
//		if (payType == CompanyPayType.OWN_MERCHANT) {
//			boolean b = account.setFrozenBalance(account.getFrozenBalance().subtract(project.getProjectamount())).updateById();
//			if (!b) return SmartResult.fail(StatusMsg.StatusMsg_199);
//		}
//
//		zhiduoduoProjectService.handleCompanyOrderAfter(project);
//		// return order.updateById() ? smartResult(StatusMsg.StatusMsg_100) : smartResult(StatusMsg.StatusMsg_199);
//		return SmartResult.success();
//	}
//
//	@Override
//	public SmartResult handlePayJiugeCharge(CompanyProject project) {
//		Integer projectid = project.getProjectid();
//		Integer userid = project.getUserid();
//		CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", project.getCompid()));
//
//		//实际给九歌的手续费金额. 减去1.5元,是开联通扣掉的转账手续费. 对公1元,对创客个人0.5元,对创客公户1元
//		//专票项目，使用对公账户，普票项目，使用个人账户
//		BigDecimal payJiugeCharge = zhiduoduoProjectService.getPayJiugeCharge(project);
//		if (payJiugeCharge.doubleValue() <= 0) {
//			throw SmartException.of(StatusMsg.StatusMsg_455);
//		}
//
//		//支付记录,检查是否已存在还未处理好的支付记录.如果有,那么需要等待
//		//支付创建中,处理中和处理成功,表示不需要再新建了.直接返回
//		int recordProcessing = new TradeRecord().selectCount(Condition.create()
//				.eq("projectid", projectid)
//				.eq("idtype", UserType.MAKER)
//				.eq("business_type", Constants.KLT_PAY_BUSINESS_TYPE_JIUGE_CHARGE)
//				.in("tradestate", Arrays.asList(Constants.TRADE_CREATE, Constants.TRADE_IN_PROCESS)));
//		if (recordProcessing > 0) {
//			throw SmartException.of(StatusMsg.StatusMsg_448);
//		}
//		int recordSuccess = new TradeRecord().selectCount(Condition.create()
//				.eq("projectid", projectid)
//				.eq("idtype", UserType.MAKER)
//				.eq("business_type", Constants.KLT_PAY_BUSINESS_TYPE_JIUGE_CHARGE)
//				.eq("tradestate", Constants.TRADE_SUCCESS));
//		if (recordSuccess > 0) {
//			throw SmartException.of(StatusMsg.StatusMsg_449);
//		}
//
//		String purpose = project.getProjectname() + "-平台服务费";
//		if (purpose.length() > 16) {
//			purpose = purpose.substring(0, 16);
//		}
//
//		// 2020.6.6 根据项目的支付方式,确定商户号id:九歌统一账户或者企业自己的商户号
//		String merchantid;
//		int payAccount;
//
//		if (project.getPayType() != CompanyPayType.OWN_MERCHANT && StringUtil.isEmpty(companyAccount.getMerchantid())) {
//			// 没有绑定商户号, 报错,直接回滚所有操作
//			throw SmartException.of(StatusMsg.StatusMsg_329);
//		}
//		merchantid = companyAccount.getMerchantid();
//		payAccount = PayAccount.OWN_MERCHANT;
//
//		TradeRecord trade = new TradeRecord().setAcctname(kltPayConfig.getJiugeAccountName())
//				.setAcctno(kltPayConfig.getJiugeAccountNo())
//				.setBankname(kltPayConfig.getJiugeBankName())
//				.setBankno(kltPayConfig.getJiugeBankNo())
//				.setAccttype(2)
//				.setMerchantid(merchantid)
//				.setPurpose(purpose)
//				.setTradeamount(payJiugeCharge)
//				.setTradeno(RandomUtil.createRandomNo("PAY", ""))
//				.setTradetime(new Date())
//				.setTradetype(Constants.TRADE_TYPE_PAYMENT)
//				.setPayAccount(payAccount)
//				.setBusinessType(Constants.KLT_PAY_BUSINESS_TYPE_JIUGE_CHARGE)
//				.setProjectid(projectid)
//				.setIdtype(1)
//				.setUserid(userid);
//
//		if (trade.insert()) {
//			return kltPayService.doCallPayApi(trade);
//		}
//		throw SmartException.of(StatusMsg.StatusMsg_445);
//	}
//
//	@Override
//	public void doAfterPayJiugeTradeSucceed(CompanyProject project, TradeRecord trade) {
//		try {
//			coreBrokerageService.handleZhiduoduoProjectPartnerBrokerage(project, trade.getTradeid(), trade.getTradeno());
//		} catch (Exception e) {
//			//报错,回滚
//			log.error("doAfterPayJiugeTradeSucceed 报错:", e);
//			throw new RollbackException("处理合伙人佣金失败");
//		}
//
//	}
//
//	private BigDecimal getPayUserAmount(CompanyProject project) {
//		//实际给创客的金额
//		return project.getProjectdealamount()
//				.subtract(project.getProjectservicecharge())
//				.subtract(project.getProjecttaxfee());
//	}
//}
